package hooks

import (
	"context"
	"fmt"
	"os"

	log "atomgit.com/atomgit_dev/alog/alogcore"
	"atomgit.com/atomgit_dev/git-hooks/pkg/config"
	"atomgit.com/atomgit_dev/git-hooks/pkg/internal/agitext"
	pb "atomgit.com/atomgit_dev/satellite-proto/go"
)

// StartPreAutoGC calls satellite.PreAutoGCHook to execute pre-auto-gc hook.
func StartPreAutoGC(ctx context.Context) (int, error) {
	return preAutoGC(ctx)
}

func preAutoGC(ctx context.Context) (int, error) {
	repository, err := agitext.GetPbRepositoryFromEnv()
	if err != nil {
		return 1, fmt.Errorf("fail to extract pb.Repository from env: %w", err)
	}

	log.Info(ctx, "begin to execute pre-auto-gc hook",
		log.NewField("RepositoryID", repository.GlRepositoryId),
	)

	conn, err := getSatelliteConn()
	if err != nil {
		return 1, fmt.Errorf("fail to create grpc client for pre-send-pack: %w", err)
	}
	defer conn.Close()

	// Using PreReceiveTimeout as timeout
	ctx, cancel := context.WithTimeout(ctx, config.Cfg.PreReceiveTimeout)
	defer cancel()
	if _, err := pb.NewHookServiceClient(conn).PreAutoGCHook(ctx, &pb.PreAutoGCHookRequest{
		Repository:           repository,
		EnvironmentVariables: os.Environ(),
	}); err != nil {
		return 1, fmt.Errorf("fail to run pre-auto-gc hook: %w", err)
	}

	// return 1 to prevent running git-gc
	return 1, nil
}
